﻿using System.Collections.Concurrent;

namespace sgf.server
{
    public abstract class NetChannel
    {
        protected readonly CancellationTokenSource CloseSrc = new();

        public virtual void Write(byte[] data)
        {
        }

        protected virtual void Close()
        {
            CloseSrc.Cancel();
        }

        public virtual bool IsClose()
        {
            return CloseSrc.IsCancellationRequested;
        }

        public virtual string remoteAddress { get; protected init; } = "";

        public virtual Task StartAsync()
        {
            return Task.CompletedTask;
        }


        readonly ConcurrentDictionary<string, object> datas = new();

        public T? GetData<T>(string key)
        {
            if (datas.TryGetValue(key, out var v))
            {
                return (T)v;
            }

            return default;
        }

        public void RemoveData(string key)
        {
            datas.Remove(key, out _);
        }

        public void SetData(string key, object v)
        {
            datas[key] = v;
        }
    }
}